var http = require('http');
var fs = require('fs');
var url = require('url');
var mime = require('./mime');
var path = require('path');
var os = require('os');
// 获取本机IP地址
const networkInterfaces = os.networkInterfaces();
for (const interfaceName in networkInterfaces) {
    networkInterfaces[interfaceName].forEach((interface) => {
        if (interface.family === 'IPv4' && !interface.internal) {
            console.log(`Interface: ${interfaceName}, IP Address: ${interface.address}`);
        }
    });
}


// http://localhost:5363/index.html
var server = http.createServer((req, res) => {
    // const url = req.url
    var reqUrl = decodeURIComponent(req.url); // 对 URL 进行解码
    var filePath = './page' + url.parse(reqUrl).pathname;
    console.log(filePath)
    if (filePath === './page') filePath = './index.html';
    if (fs.existsSync(filePath)) {
        var data = fs.readFileSync(filePath);
        var extname = path.extname(filePath);
        var contentType = mime[extname];

        res.writeHead(200, {
            'content-type': contentType
        });
        res.write(data);
        res.end();
    } else {
        res.writeHead(404, { 'content-type': 'text/plain' });
        res.end('404 Not Found');
    }
});

server.listen(5363, () => {
    console.log('Listening on port 5362');
});
